# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

library(ggplot2)
library(data.table)
library(optparse)
library(ropls)
library(magrittr)
library(tibble)
library(tidyverse)
library(extrafont)

option_list <- list(
  make_option("--i", default = "AllMet_with_Anno.txt", type = "character", help = "metabolite data file"),
  make_option("--g", default = "group.txt", type = "character", help = "sample group file"),
  make_option("--sc", default = "Class_Color.txt", type = "character", help = "sample color file"),
  make_option("--mc", default = "meta_color.txt", type = "character", help = "metabolite color file"),
  make_option("--pc", default = "sampleBar_plot_config.txt", type = "character", help = "config file")

)
opt <- parse_args(OptionParser(option_list = option_list))
font_import(paths = c("/usr/share/fonts/myFonts"), recursive = F, prompt = F)

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/parse_config.R"))
fontFamily <- configGet(plotConfigData, "fontFamily")
baseFamily <- fontFamily

sampleInfo <- read_tsv(opt$g) %>%
  rename(SampleID = Sample) %>%
  select(c("SampleID", "ClassNote"))

data <- read_tsv(opt$i) %>%
  select(-c("HMDB", "KEGG", "Metabolite"))

df <- data %>%
  group_by(Class) %>%
  summarise_all(sum) %>%
  mutate_at(vars(-"Class"), function(x) { x * 100 / sum(x) }) %>%
  gather("SampleID", "Value", -Class)

sampleColDf <- read_tsv("Class_Color.txt") %>%
  select(c("ClassNote", "col"))

sampleInfo

sortSamplesDf <- sampleInfo %>%
  left_join(sampleColDf, by = c("ClassNote")) %>%
  mutate(ClassNote = factor(ClassNote, levels = unique(sampleInfo$ClassNote))) %>%
  arrange(ClassNote) %>%
  mutate(Id = 1:n())

sortSamplesDf

uniqClassNotes <- unique(sortSamplesDf$ClassNote)

print("===")
df <- df %>%
  inner_join(sortSamplesDf, by = c("SampleID")) %>%
  arrange(ClassNote)

metaColDf <- read_tsv(opt$mc) %>%
  select(c("Class", "col"))
metaCols <- metaColDf %>%
  deframe()

defaultWidth <- 10 + max(0, nrow(sampleInfo) - 20) * 0.1
finalWidth <- getFinalWidth(width, defaultWidth, opt$pc)

pdf("Class_Barplot_by_Sample.pdf", width = finalWidth, height = height)

pdf <- df

pdf

yPos <- 104
pOffset <- 0.5
annoYPos <- 107
yBreaks <- seq(0, 100, by = 25)

sortSamples <- unique(pdf$SampleID)
sortSamples

p <- ggplot(pdf, mapping = aes(x = Id, y = Value, fill = Class)) +
  xlab("") +
  ylab("Relative Abundance(%)") +
  theme_bw(base_size = 8.8, base_family = baseFamily) +
  theme(axis.text.x = element_text(angle = 90, size = 8, hjust = 1, vjust = 0.5), panel.grid.minor = element_blank(),
        axis.text.y = element_text(size = 15), legend.position = 'bottom', panel.grid.major = element_blank(),
        panel.border = element_blank(), axis.title.y = element_text(size = 15),
        legend.margin = margin(t = 0.3, b = 0.1, unit = 'cm'), axis.ticks = element_line(colour = "black", size = 0.5),
        legend.text = element_text(size = 8), axis.title.x = element_text(size = 11), legend.key.size = unit(1, "line"),
        axis.line = element_blank(), plot.margin = unit(c(0.5, 0.5, 0.5, 0.5), "cm")

  ) +
  geom_col() +
  scale_fill_manual("", values = metaCols) +
  scale_x_continuous("", labels = sortSamplesDf$SampleID, breaks = sortSamplesDf$Id, expand = c(0, 0)) +
  scale_y_continuous(breaks = yBreaks)


for (v in uniqClassNotes) {
  df <- sortSamplesDf %>%
    filter(ClassNote == v)
  id <- df$Id
  x = id[1]
  xend = id[length(id)]
  col <- unique(df$col)
  p <- p + geom_segment(aes_string(x = (x - pOffset), xend = (xend + pOffset), y = yPos, yend = yPos), colour = col,
                        linetype = "solid", size = 3)
  p <- p + annotate("text", x = median(id), y = annoYPos, label = v, hjust = 1, size = 5, family = baseFamily)
}

p <- getBasicPlotArg(p)

if (!is.na(legendTitle)) {
  p <- p +
    guides(fill = guide_legend(title = legendTitle))
}

p

dev.off()
